import 'package:easy_refresh/easy_refresh.dart' hide Header;
import 'package:flutter/material.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:todo_app/controllers/TodoController.dart';
import 'package:todo_app/hooks/EasyRefreshController.dart';
import 'package:todo_app/layout/Gaps.dart';
import 'package:todo_app/layout/Header.dart';
import 'package:todo_app/pages/todo/components/TodoWidget.dart';
import 'package:todo_app/utils/ExtHelper.dart';

import '../../controllers/definitions/TodoModel.dart';

class TodoCollectListPage extends HookWidget {
  const TodoCollectListPage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    var pageData = useState<PageData<TodoModel>>(PageData<TodoModel>());
    var pagination = useState<Pagination>(Pagination());
    var controller = useEasyRefreshController(
      controlFinishRefresh: true,
      controlFinishLoad: true
    );

    useEffect(()  {
      TodoController.collectListUsingGet(pageData.value.current, pageData.value.pageSize).then((res) {
        if(res.status == 'success') {
          var data = PageData<TodoModel>();
          data.current = res.data?.current ?? 1;
          data.total = res.data?.total ?? 0;
          data.pageSize = pageData.value.pageSize;
          data.data = pageData.value.data;
          data.records = pageData.value.records;
          if(data.current == 1) {
            controller.finishRefresh();
            data.firstPage(res.data?.records ?? []);
          } else {
            data.addPage(data.current, res.data?.records ?? []);
          }
          pageData.value = data;
          if(data.hasMore) {
            controller.finishLoad();
          } else {
            controller.finishLoad(IndicatorResult.noMore, true);
          }
        }
      });
      return () {};
    }, [pagination.value.current, pagination.value.refreshKey]);


    return Scaffold(
      appBar: const Header(title: "收藏"),
      body: EasyRefresh(
        controller: controller,
        onRefresh: () {
          var clone = pagination.value.clone();
          clone.current = 1;
          clone.refreshKey += 1;
          pagination.value = clone;
        },
        onLoad: () {
          if(pageData.value.hasMore) {
            var clone = pagination.value.clone();
            clone.current += 1;
            pagination.value = clone;
          }
        },
        child: CustomScrollView(
          slivers: [
            SliverToBoxAdapter(
              child: Gaps.vGap10
            ),
            SliverList.list(
              children: pageData.value.data.map<Widget>((todo) => TodoWidget(todo: todo)).toList()
            )
          ],
        )
      )
    );
  }
}